<template>
    <el-dialog title="选择部门" :visible="true" width="800px" @close="cancel()" append-to-body> 
        <div>
            <div class="choiceList">
                <div>
                    <el-tag
                        v-for="tag in tags"
                        :key="tag.id"
                        @close="handleClose(tag)"
                        closable>
                        {{tag.name}}
                    </el-tag>
                </div>
            </div>
            <div class="treeContent">
                <div class="head-container">
                    <el-input v-model="deptName" placeholder="部门名称（只搜索已加载数据）" clearable size="small" prefix-icon="el-icon-search" style="margin-bottom: 20px" />
                </div>
                <div class="head-container-tree">
                <el-tree :data="deptOptions" :props="defaultProps" :expand-on-click-node="false" node-key="id"  :show-checkbox='multiple' :highlight-current='!multiple'
                        ref="tree" default-expand-all   :check-strictly="true"  @check-change="handleCheckChange" :render-content="renderContent" :filter-node-method="filterNode"/>
                </div>
            </div>
            <div class="button">
                <el-button  @click="cancel">取消</el-button> 
                <el-button @click="clear">清空</el-button> 
                <el-button type="primary" @click="select">选择</el-button> 
            </div>
        </div>
    </el-dialog>
</template>

<script>
import {listSimpleDepts} from "@/api/system/dept";
import {listSimplePosts} from "@/api/system/post";
import {
    geDeptList,
} from '@/api/custom/formDesigner'
export default {
    data() {
        return {
            closeFlag: true,
            tags: [],
            // 遮罩层
            loading: true,
            // 部门名称
            deptName: undefined,
            defaultProps: {
                children: "children",
                label: "name"
            },
            deptOptions:[],
            showCheckBox:false,
            checkLabel:''     ,
        }
    },
    props: ['tagsList','multiple'],
    watch: {
        // 根据名称筛选部门树
        deptName(val) {
            this.$refs.tree.filter(val);
        },
    },
    created() {
        this.getTreeselect();
    },
    methods: {
        filterNode(value, data) {
            if (!value) return true;
            return data.name.indexOf(value) !== -1;
        },
         /** 查询部门下拉树结构 + 岗位下拉 */
        async getTreeselect () {
          // console.log(this.tagsList,'this.tagsList')
            const {data} = await geDeptList([])
            if(typeof this.tagsList[0]==='object'){
              let arr = data.filter((item)=>{
                return this.tagsList.some(val=>{
                  return val.id===item.id;
                });
              });
              this.$emit('updateTag',JSON.parse(JSON.stringify(arr)));
            }else{
              let arr = data.filter((item)=>{
                let a = this.tagsList.some(val=>{
                return (val==item.id || val==item.name);
                });
                return a;
                // if(typeof item.id  === 'number'){
                //   let a =this.tagsList.includes(item.id) || this.tagsList.includes(item.name)
                //   return (this.tagsList.includes(String(item.id)) || this.tagsList.includes(item.name));
                // }
              }); 
              this.$emit('updateTag',JSON.parse(JSON.stringify(arr)));
            }
            this.deptOptions = [];
            this.deptOptions.push(...this.handleTree(data, "id"));
            // const {data:data1} = await listSimplePosts()
            // this.postOptions = [];
            // this.postOptions.push(...data1);
            const that=this
            this.$nextTick(()=>{
                // console.log(that.tagsList)
                that.tags = [...that.tagsList]
                // console.log(that.tags )
                that.multiple ?that.$refs.tree.setCheckedNodes(that.tagsList):
                that.checkLabel=that.tagsList[0]?.id
                
            })
            
        },
        handleCheckChange(data, checked, indeterminate) {
            this.tags = this.$refs.tree.getCheckedNodes()
        },
        clear() {
            // this.tags = []
            // this.$refs.tree.setCheckedKeys([]);
            // this.$refs.tree.setCurrentKey()
            // this.checkLabel=null
        },
        handleClose(tag) {
            this.tags.splice(this.tags.indexOf(tag), 1)
            this.multiple ?this.$refs.tree.setCheckedNodes(this.tags):this.checkLabel=null
        },
        cancel() {
            this.clear()
            this.$emit('closeDialog')
        },
        select() {
            this.$emit( 'departmenInfo',this.tags )
            this.cancel()
        },
        renderContent(h, { node, data, store }) {
            const {id,name}=node.data
            return (
            <span class="custom-tree-node">
                {
                    this.multiple ? <span>{name}</span>:<el-radio label={id} value={this.checkLabel}  on-change={() => this.getCurrentRow(node)}>{name}</el-radio>
                }
            </span>);
        },
        getCurrentRow(node){
            this.checkLabel=node.data.id
            this.tags=[]
            this.$nextTick(() => {
                this.tags.push(node.data)
            })
        }
    }
}
</script>

<style lang="scss" scoped>
    .choiceList{
        border: 1px dashed;
        height: 50px;
        padding: 10px 20px;
    }
    .choiceList .el-tag+.el-tag{
        margin-left: 10px;
    }
    .treeContent{
        // display: flex;
        margin-top: 20px;
    }
    .button{
        text-align: right;
        margin-top: 20px;
    }
    .head-container-tree{
        height: 240px;
        overflow: auto;
    }
</style>